/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.tilesConfig;

import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.util.core.TileContainerUtil;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.service.core.LayoutManager;
import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.search.SearchManager;
import org.apache.struts.action.*;
import org.apache.commons.validator.GenericValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import java.util.Collection;
import java.util.Iterator;

/**
 * <p>Reloads tiles config from config files. All changes made through admin
 * console will be lost.
 * <p><a href="ReloadTilesConfigAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.3 $ $Date: 2007/12/19 21:09:04 $
 * @struts.action path="/core/tilesConfig/reload"
 * validate="false"
 * roles="core-globalOperations-reloadTilesConfig"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/globalProperty/list.do"
 */
public class ReloadTilesConfigAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request,
                                 HttpServletResponse response)
            throws Exception {

		// discard all config changes
        ServletContext servletContext = servlet.getServletContext();
        TileContainerUtil.getInstance(servletContext).reloadTilesConfig();

        LayoutManager layoutManager
                = (LayoutManager) getBean(Constants.LAYOUT_MANAGER_BEAN);
        Collection layouts = layoutManager.listLayouts(null); 

        //flush cache, reindex
        CacheUtil cacheUtil = CacheUtil.getInstance(request);
        SearchManager searchManager
                = SearchManager.getInstance(servletContext);

        cacheUtil.flushFieldIndices();
        cacheUtil.flushMenuCache();

        Iterator i = layouts.iterator();
        while (i.hasNext()) {
            Layout layout = (Layout) i.next();
            cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());
            cacheUtil.flushLayoutSequenceCache(layout.getDefinition());
            Iterator cpIterator = layout.getContentPages().iterator();
            while (cpIterator.hasNext()) {
                ContentPage contentPage = (ContentPage) cpIterator.next();
                searchManager.unIndexPage(contentPage.getUri(), request);
                if (contentPage.getActive().booleanValue()) {
                    searchManager.indexPage(contentPage, request);
                    CacheUtil.ContentPageData cpd = new CacheUtil.ContentPageData(contentPage.getId(), layout.getCpDefinition(), WebappUtil.rolesToString(contentPage.getRoles()), contentPage.getCacheMaxAge());
                    cacheUtil.putContentPageInCache(cpd, contentPage.getUri());
                }
            }
        }

        ActionMessages messages = new ActionMessages();
        messages.add("operationSuccessful", new ActionMessage("core.globalOperation.messages.reloadTilesConfigSuccessful"));
        saveMessages(request, messages);

		String redirectUrl = request.getParameter("redirectUrl");
		if ( !GenericValidator.isBlankOrNull(redirectUrl) ) {
			ActionForward redirect = new ActionForward();
			redirect.setRedirect(true);
			redirect.setPath(redirectUrl);
			return redirect;
		} else {
			return mapping.findForward("admin");
		}
	}
}
